package com.itcanteen.medical.common.advice;

import com.itcanteen.medical.common.annotation.IgnoreResponseAdvice;
import com.itcanteen.medical.common.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 增强
 * @author TeamOne
 * @date 2020/12/8 10:30
 */
@RestControllerAdvice(basePackages = "com.itcanteen.medical.patient.controller")
@Slf4j
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断是否需要增强
     * @param returnType 返回类型
     * @param converterType 转换类型
     * @return 返回是否执行
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("CommonResponseDataAdvice->supports");
       if(returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        return !Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(IgnoreResponseAdvice.class);
    }


    /**
     * 增强的逻辑:拦截@@RestController的类，拿到返回结果，进行增强
     * @param body 返回对象
     * @param returnType 返回类型
     * @param selectedContentType 查询类型
     * @param selectedConverterType 查询转换类型
     * @param request 请求
     * @param response 响应
     * @return 返回统一结果
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        log.info("body->{}",body);

        CommonResponse<Object> commonResponse = new CommonResponse<>(0, "success");
        if(body==null){
            return commonResponse;
        }else if(body instanceof CommonResponse){
            commonResponse =  (CommonResponse<Object>)body;
        }else{
            commonResponse.setData(body);
        }
        return commonResponse;
    }
}
